package com.ruibo.modules.quartz.utils;

import com.ruibo.utils.SpringContextHolder;
import com.ruibo.utils.ThrowableUtil;
import com.ruibo.config.thread.ThreadPoolExecutorUtil;
import com.ruibo.modules.quartz.domain.QuartzJob;
import com.ruibo.modules.quartz.domain.QuartzLog;
import com.ruibo.modules.quartz.repository.QuartzLogRepository;
import com.ruibo.modules.quartz.service.QuartzJobService;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @ClassName ExecutionJob
 * @Description
 * 那么如何给job实例增加属性或配置呢？如何在job的多次执行中，跟踪job的状态呢？答案就是:JobDataMap，
 *  JobDetail对象的一部分。  这个是异步执行的
 * @Author SunFeng
 * @Date 2020/2/28 15:24
 * @Version 1.0
 */
public class ExecutionJob extends QuartzJobBean {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    // 默认使用 juc包下的线程池   也可以使用spring中自带的线程池
    private final static ThreadPoolExecutor EXECUTOR = ThreadPoolExecutorUtil.getPoll();

    /**
     * 实现Job的逻辑
     * @param context
     */
    @Override
    protected void executeInternal(JobExecutionContext context) {
            //
        QuartzJob quartzJob = (QuartzJob) context.getMergedJobDataMap().get(QuartzJob.JOB_KEY);


        // 获取spring bean
        QuartzLogRepository quartzLogRepository = SpringContextHolder.getBean(QuartzLogRepository.class);
        QuartzJobService quartzJobService = SpringContextHolder.getBean(QuartzJobService.class);

        QuartzLog log = new QuartzLog();
        //任务名称
        log.setJobName(quartzJob.getJobName());
        //Bean名称
        log.setBeanName(quartzJob.getBeanName());
        //方法名称
        log.setMethodName(quartzJob.getMethodName());
        // 参数
        log.setParams(quartzJob.getParams());
        long startTime = System.currentTimeMillis();
        //Cron表达式
        log.setCronExpression(quartzJob.getCronExpression());
        try {
            // 执行任务
            logger.info("任务准备执行，任务名称：{}", quartzJob.getJobName());
            QuartzRunnable task = new QuartzRunnable(quartzJob.getBeanName(), quartzJob.getMethodName(),
                    quartzJob.getParams());
            Future<?> future = EXECUTOR.submit(task);
            future.get();
            long times = System.currentTimeMillis() - startTime;
            log.setTime(times);
            // 任务状态
            log.setIsSuccess(true);
            logger.info("任务执行完毕，任务名称：{} 总共耗时：{} 毫秒", quartzJob.getJobName(), times);
        } catch (Exception e) {
            logger.error("任务执行失败，任务名称：{}" + quartzJob.getJobName(), e);
            long times = System.currentTimeMillis() - startTime;
            log.setTime(times);
            // 任务状态 0：成功 1：失败
            log.setIsSuccess(false);
            log.setExceptionDetail(ThrowableUtil.getStackTrace(e));
            quartzJob.setIsPause(false);
            //更新状态
            quartzJobService.updateIsPause(quartzJob);
        } finally {
            quartzLogRepository.save(log);
        }
    }
}
